package com.gcxy.security.handler;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.gcxy.utils.UserUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * @Author qinlun
 * @Date 2021/4/25 15:36
 * Description 字段自动填充
 */
@Slf4j
@Component
public class MetaObjectHandler implements com.baomidou.mybatisplus.core.handlers.MetaObjectHandler {

    /**
     * 新增时填充字段
     *
     * @param metaObject
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        this.strictInsertFill(metaObject, "createTime", LocalDateTime.class, LocalDateTime.now());
        this.strictInsertFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());
        try {
            this.strictInsertFill(metaObject, "updater", String.class, UserUtil.getCurrentUser().getUsername());
        } catch (NullPointerException e){
            log.error("获取用户信息失败：" + e);
        }
    }

    /**
     * 修改时填充字段
     *
     * @param metaObject
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        this.setFieldValByName("updateTime", LocalDateTime.now(), metaObject);
        try {
            this.setFieldValByName("updater", UserUtil.getCurrentUser().getUsername(), metaObject);
        } catch (NullPointerException e){
            log.error("获取用户信息失败：" + e);
        }
    }
}
